package ie.dcu.spca.data.db;

import java.util.List;

import ie.dcu.spca.data.BillDataManager;
import ie.dcu.spca.data.ItemDataManager;
import ie.dcu.spca.data.ProductDataManager;
import ie.dcu.spca.model.Bean;
import ie.dcu.spca.model.bean.Bill;
import ie.dcu.spca.model.bean.Item;
import ie.dcu.spca.model.bean.Product;
import ie.dcu.spca.model.dao.BillDao;

public class DBBillDataManager extends DBBasicDataManager implements
        BillDataManager {

    private static BillDao bDao = new BillDao();

    private BillDao billDao() {
        return bDao;
    }

    public DBBillDataManager() {
        super();
    }

    @Override
    public int create(String location, int payerId) {
        return billDao().insertBill(location, payerId);
    }

    @Override
    public List<Bill> get() {
        return (List) billDao().selectAllBean();
    }

    @Override
    public Bill get(int id) {
        return (Bill) billDao().selectById(id);
    }

    @Override
    public void update(int id, String location, int payerId) {
        Bill bill = (Bill) billDao().selectById(id);
        bill.setLocation(location);
        bill.setUser_id(payerId);
        billDao().updateByBean(bill);
    }

    @Override
    public void delete(int id) {
        billDao().deleteById(id);
    }

    @Override
    public List<Bean> getBeanList() {
        return (List) get();
    }

    @Override
    public int getId(Bean bean) {
        return ((Bill) bean).getId();
    }

    @Override
    public String getName(Bean bean) {
        Bill bill = (Bill) bean;
        return bill.getLocation() + bill.getCreate_at().toLocaleString();
    }

    @Override
    public String getSummary(int id, ItemDataManager itemManager,
            ProductDataManager productManager) {
        StringBuffer sb = new StringBuffer();
        sb.append("Total Price:");

        List<Item> itemList = itemManager.getByBillId(id);
        double tot = 0;
        for (Item item : itemList) {
            Product product = productManager.get(item.getProduct_id());
            tot += itemManager
                    .priceFormat(product.getPrice() * item.getCount());
        }
        sb.append(itemManager.priceFormat(tot));
        return sb.toString();
    }

}
